package com.mitake.servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ComputerFacilitiesServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

	public ComputerFacilitiesServlet()
	{
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType(CONTENT_TYPE);
		request.setCharacterEncoding(response.getCharacterEncoding());
		
		String event = request.getParameter("event");
		String src = request.getParameter("src");
		
		ServletContext context = getServletContext();

		String rootPath = context.getRealPath("");
		String filename = rootPath + "/setting";
		
		File file = new File(filename);

		if(!file.exists())
		{
			file.mkdirs();
		}

		String data = "";
		filename = filename + "/cf.ini";
		
		file = null;
		file = new File(filename);
		
		if(!file.exists())
		{
			file.createNewFile();
		}
		
		if(event.equals("s"))
		{
			FileOutputStream fos = new FileOutputStream(filename);
			fos.write(src.getBytes("utf-8"));
			fos.flush();
			fos.close();
			
			StringBuilder tmp = new StringBuilder();
			tmp.append("{");
			tmp.append("\"code\":\"00000\",");
			tmp.append("\"message\":\"ok\",");
			tmp.append("\"host\":");
			tmp.append(src.length() > 0 ? src : "\"\"");
			tmp.append("}");
			
			data = tmp.toString();
		}
		else if(event.equals("g"))
		{
			FileInputStream fis = new FileInputStream(filename);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			byte[] b = new byte[1024];
			int len;
			
			while((len = fis.read(b, 0, 1024)) > -1)
			{
				baos.write(b, 0, len);
			}
			
			fis.close();
			
			String content = new String(baos.toByteArray(), "utf-8");
			
			StringBuilder tmp = new StringBuilder();
			tmp.append("{");
			tmp.append("\"code\":\"00000\",");
			tmp.append("\"message\":\"ok\",");
			tmp.append("\"host\":");
			tmp.append(content.length() > 0 ? content : "\"\"");
			tmp.append("}");
			
			data = tmp.toString();
		}
		
        PrintWriter out = response.getWriter();
        out.println(data);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doGet(request, response);
	}
}
